<?php
class Report {
	static function validate($db,$isEditing=false) {
		$res['state'] = true;
		$res['error'] = array();

		$p = $_POST;
		if(!isset($p)) {
			$res['state'] = false;
			return $res;
		}
		if(!(isset($p["name"]) && !empty($p["name"]) && strlen(utf8_decode($p["name"])) > 2 && strlen(utf8_decode($p["name"])) < 500)) {
			$res['state'] = false;
			$res['error']['name'] = 1;
		} else if(!$isEditing){
			$a = $db -> query("select `name` from `report` where `name`='" . $p['name'] . "'") -> fetchAll();
			if(!empty($a)) {
				$res['state'] = false;
				$res['error']['name'] = 1;
			}
		}
		
		if(!(isset($p["section"]) && !empty($p["section"]) && $p['section']>=0)) {
			$res['state'] = false;
			$res['error']['section'] = 1;
		}
		
		if(!(isset($p["text"]) && !empty($p["text"]) && strlen($p["text"]) > 2)) {
			$res['state'] = false;
			$res['error']['text'] = 1;
		}
		return $res;
	}
	
	static function get($db="",$name="",$id=-1,$where="",$field="*"){
		if($db=="")$db=DB::get();
		$sql = "select ".$field." from `report`";
		if($where!=""){
			$where=" where ".$where;
		}else if($name!=""){
			$where=" where `name`='".$name."'";
		}else if($id>0){
			$where=" where `id`='".$id."'";
		}
		if($where!=""){
			if(User::checkAccess('developer')){
				$where=$where;
			}else if(User::checkAccess('admin')){
				$where.=" and `state`<>-1";
			}else{
				$where.=" and (`state`=1".(isset($_SESSION['user'])&&isset($_SESSION['user']['person'])&&isset($_SESSION['user']['person']['id'])?" or (`state`=0 and `author`='".$_SESSION['user']['person']['id']."')":"").")";
			}
		}
		return DB::query($sql.$where);
	}
	
	static function set($db,$data,$name="",$id=-1){
		$sql = "update `report` set";
		$where = " where ";
		$comma = "";
		if(($name==""&&$id<0)||empty($data))return false;
		if($name!=""){
			$where.="`name`='".$name."'";
		}else if($id>0){
			$where.="`id`='".$id."'";
		}
		foreach ($data as $key => $value) {
			if(!is_string($value))continue;
			$val = trim($value);
			$sql.= $comma."`".$key."`='".$val."'";
			$comma=",";
		}
		$st=$db->prepare($sql.$where);
  		$st->execute();
		return true;
	}
	
	static function delete($id){
		DB::exec_("delete from `report` where `id`='".$id."'");
	}
	
	static function getReportTags($db,$name="",$id=-1){
		$tags_ids 	= Report::get($db,$name,$id);
		$where 		= preg_replace("/^or/i","",str_replace(","," ",preg_replace("/([^,]+)/i", "or id='$1'", $tags_ids[0]['tags'])));
		return Tag::get($db,"",-1,"*",$where."");
	}
	
	static function getMainLinkButton($name,$id){
		return '<a class="but ui-off" data-url="report/list_" data-action="function(){$(\'#tabs-content\').tabs(\'select\',\'tabs-id-section\');}")}" data-opt=\'{"action":"load","target":"#tabs-id-section","postData":{"id":"'.$id.'"}}\'>'.$name."</a>";
	}
	
	static function getViewData($db="",$reports="",$id=-1){
		$db = $db==""?DB::$db:$db;
		$result 	= "";
		$report 	= array();
		$admin 		= User::checkAccess('admin');
		foreach($reports as $report){
			$author 			= Person::get($db,$report['author']);
			$is_author 			= User::checkAccess("",$author['id'])&&$report['state']==0;
			$report['author'] 	= Person::getFio($author);
			$report['logo']		= $author['users'][0]['logo'];
			$report['degree'] 	= isset($author['degree'])&&$author['degree']!=""?"<div><span class='b'>Звание:</span> ".$author['degree']."</div>":"";
			$report['post'] 	= isset($author['post'])&&$author['post']!=""?"<div><span class='b'>Должность:</span> ".$author['post']."</div>":"";
			$tags 				= Report::getReportTags($db,"",$report['id']);
			$report['tags'] 	= Tag::getViewData($tags);
			$buttons 			= array();
			$dot_button 		= array();
			if($admin){
				$report['email']= "<div><span class='b'>Email:</span> <a href='mailto:".$author['email']."'>".$author['email']."</a></div>";
			}else{
				$report['email']= "";
			}
//Парсинг кнопок
//*******************************************************************************************************************************************************************************************************************************************************************************************************************************************
			if(Conference::getState()>0){
				if(!$admin&&$report['state']==0&&$author['id']!=$_SESSION['user']['person']['id'])continue;
				if($admin||$is_author){
					if($is_author)$buttons['Редактировать'] 	= array("opt"=>array("icon"=>"pencil","text"=>false,"action"=>"load","target"=>"dialog","postData"=>array("form"=>true,"id"=>$report['id'])),"url"=>"report/edit");
					$buttons['Удалить'] 						= array("opt"=>array("icon"=>"trash","text"=>false,"id"=>$report['id'],"name"=>$report['name']),"url"=>"report/delete","action"=>"deleteReport(opt,but)");
					if($report['state']==-1){
						$buttons['Удалить']['url'] 				= "report/delete_final";
					}
				}
				if($admin&&$report['state']==0){
					$buttons['Опубликовать'] 	= array("opt"=>array("icon"=>"circle-check","text"=>false,"id"=>$report['id'],"url"=>"report/publicate","name"=>$report['name']),"action"=>"publicateReport(opt,but)");
				}
			}
			if($id<0){
				$buttons['Показать'] 		= array("opt"=>array("icon1"=>"arrowthick-1-e","postData"=>array("id"=>$report['id']),"action"=>"load","target"=>"#tabs-id-section","hideEffect"=>"slide","showEffect"=>"slide"),"url"=>"report/list_");
				$dot_button['...'] 			= $buttons['Показать'];
				unset($dot_button['...']['opt']['icon1']);
				$dot_button 				= Template::getButtons($dot_button);
			}else{
				$buttons['Назад'] 			= array("opt"=>array("icon"=>"arrowthick-1-w","postData"=>array("id"=>$report['section']),"action"=>"load","target"=>"#tabs-id-section","hideEffect"=>"slide","showEffect"=>"slide"),"url"=>"section/list_");
			}
			$report['buttons'] 				= Template::getButtons($buttons);
//*******************************************************************************************************************************************************************************************************************************************************************************************************************************************
			if(!isset($report['publication_date'])){
				$report['publication_date']="";
			}else{
				$report['publication_date']="<div>Дата публикации: ".$report['publication_date']."</div>";
			}
			if($id==-1&&strlen($report['text'])>260){
				$text 			= strip_tags($report['text']);
				$text 			= mb_substr($text, 0,500,"UTF-8");
				$text 			= preg_replace("/^(.{260})([^\.]+).+$/","$1$2. ",$text);
				$report['text'] = $text.$dot_button;
			}
			
			if($report['state']==0){
				$report['state_class'] = 'b_g_2';
			}else if($report['state']==-1){
				$report['state_class'] = 'b_r_2';
			}
			
			if(isset($report['delete_date'])&&$report['delete_date']!=""){
				$report['delete_date'] = "<div class='ui-state-error'>Дата удаления: ".$report['delete_date']."</div>";
			}else{
				$report['delete_date'] = "";
			}
			
			if($id==-1){
				$result.=Template::parse_('report/main.min',$report);
			}else{
				$report['comments'] = Comment::getViewData($id);
				$result.=Template::parse_('report/main',$report);
			}
		}
		return $result;
	}
	
	static function create($db){
		if(!User::checkAccess('user')&&Conference::getState()<0)die('Ошибка доступа!!!');
		$p = $_POST;
		foreach($p as $key => $value) {
			if(is_string($value)){
				$p[$key] = trim($value);
			}
		}
		$tidy_config = array( 
                     'clean' => true,
                     'show-body-only' => true,
                     'output-html'=>true
                     ); 

		$tidy = tidy_parse_string($p['text'], $tidy_config, 'UTF8'); 
		if ($tidy->errorBuffer) {
		   $tidy->cleanRepair();
			$p['text'] = $tidy;
		}
		$sql = "insert into `report` (`name`, `text`, `author`,`creating_date`,`section`) values (?,?,?,?,?)";
		
		$pdo = DB::$db->prepare($sql);
		$pdo->execute(array($p['name'],$p['text'],$_SESSION['user']['person']['id'],date('Y-m-d H:i:s'),$p['section']));
		
		$report 	= Report::get($db,$p['name']);
		$id 	 	= isset($report[0])&&isset($report[0]['id'])?$report[0]['id']:"";
		if($id>=0){
			$tags = Tag::create($db, $_POST['tags'],$id);
			Report::set($db, array("tags"=>$tags),"",$id);
			$res = array("state" => true, "msg" => "Создание нового доклада выполнено!");
		}else{
			$res = array("state" => false, "msg" => "Создание нового доклада не выполнено!");
		}
		return $res;
	}

}
?>